package br.elsa.survey.services.impl;

import java.security.InvalidParameterException;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Stateful;
import javax.enterprise.event.Event;
import javax.inject.Inject;
import javax.persistence.PersistenceContext;

import br.elsa.survey.dao.QuestionDao;
import br.elsa.survey.dao.exceptions.DataNotFoundException;
import br.elsa.survey.domain.questions.Question;
import br.elsa.survey.services.QuestionService;
import br.elsa.survey.services.events.QuestionCreatedEvent;
import br.elsa.survey.services.events.QuestionRemovedEvent;

/**
 * Service that implements all business logic over {@link Question} domain.
 * 
 * <p>
 * This service is stateful to maintain the {@link PersistenceContext} available
 * throughout many transactions, with this, the lazy initialization of entities
 * is fixed.
 * </p>
 * 
 * @author diego
 * @since 2010-09-25
 */
@Stateful
public class QuestionServiceBean implements QuestionService {

	@EJB
	private QuestionDao questionsDao;

	@Inject
	private Event<QuestionCreatedEvent> questionCreatedEvent;

	@Inject
	private Event<QuestionRemovedEvent> questionRemovedEvent;

	/**
	 * Default constructor used by CDI to create injectable instances of this
	 * class.
	 */
	public QuestionServiceBean() {

	}

	/**
	 * Constructor used to inject mock dependencies
	 * 
	 * @param entityManager
	 * @param questionCreatedEvent
	 * @param questionRemovedEvent
	 */
	public QuestionServiceBean(QuestionDao questionsDao, Event<QuestionCreatedEvent> questionCreatedEvent, Event<QuestionRemovedEvent> questionRemovedEvent) {

		this.questionsDao = questionsDao;
		this.questionCreatedEvent = questionCreatedEvent;
		this.questionRemovedEvent = questionRemovedEvent;
	}

	/**
	 * 
	 * @see br.elsa.survey.services.ufrgs.epi.elsa.survey.services.QuestionService#create(br.ufrgs.epi.elsa.survey.domain.questions.Question)
	 */
	@Override
	public void create(Question question) {

		if (question == null) {
			throw new InvalidParameterException("The question parameter can not be null.");
		}

		questionsDao.insert(question);
		questionCreatedEvent.fire(new QuestionCreatedEvent(question));
	}

	@Override
	public void remove(Question question) {

		if (question == null) {
			throw new InvalidParameterException("The question can not be null");
		}

		questionsDao.delete(question);
		questionRemovedEvent.fire(new QuestionRemovedEvent(question));
	}

	@Override
	public List<Question> getAllQuestions() throws DataNotFoundException {

		return questionsDao.findAll();
	}

}
